package cuckoo.ioc.scanner.impl;

import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;

import cuckoo.ioc.scanner.ClassesScanner;
import cuckoo.util.ClassUtil;

public class JarClassesScanner implements ClassesScanner {

	@Override
	public Set<Class<?>> doScan(String base, URL url) throws IOException {
		Set<Class<?>> classes = new HashSet<Class<?>>();

		JarURLConnection conn = (JarURLConnection) url.openConnection();
		Enumeration<JarEntry> entries = conn.getJarFile().entries();
		while (entries.hasMoreElements()) {
			JarEntry entry = entries.nextElement();
			if (entry.isDirectory() || !entry.getName().startsWith(base))
				continue;

			if (entry.getName().endsWith(".class")) {
				Class<?> clazz = ClassUtil.getClassAsResource(formatClassName(entry.getName()));
				if (clazz != null)
					classes.add(clazz);
			}
		}
		return classes;
	}

	private String formatClassName(String path) {
		return path.split("\\.")[0].replace('/', '.');
	}

}
